package com.rich.dmr.databases;

import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.util.Log;

import java.util.Objects;

public class DmrProviderContent extends ContentProvider {
    private String TAG="rich---DmrProviderContent";
    private SQLiteDatabase mSqLiteDatabase;
    private static UriMatcher matcher=new UriMatcher(UriMatcher.NO_MATCH);
    private ContentResolver contentProvider;
    static{
        matcher.addURI("com.provider.dmr.app", "frequency", 0);
        matcher.addURI("com.provider.dmr.app", "frequency/#", 1);
    }

    public DmrProviderContent() {
        super();
    }
    @Override
    public boolean onCreate() {
        DataBaseConnection mDataBaseConnection = new DataBaseConnection(getContext());
        mSqLiteDatabase= mDataBaseConnection.getWritableDatabase();
        contentProvider = Objects.requireNonNull(getContext()).getContentResolver();
        return true;
    }

    @Override
    public Cursor query(@NonNull Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        int op=matcher.match(uri);
        if (op == 0) {
            Cursor cursor = mSqLiteDatabase.query("frequency", null, selection, selectionArgs, null, null, "channel asc");
            Log.d(TAG, "cursor:" + cursor.getCount());
            return cursor;
        }
        return null;
    }

    @Override
    public String getType(Uri uri) {

        return uri.toString();
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        int op=matcher.match(uri);
        //增加
        if (op == 0) {
            mSqLiteDatabase.insert("frequency",null,values);
            contentProvider.notifyChange(uri, null);
            return Uri.withAppendedPath(uri, "ok");
        }
        return null;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        int op=matcher.match(uri);
        if (op == 0) {
            int res = mSqLiteDatabase.delete("frequency",selection,selectionArgs);
            contentProvider.notifyChange(uri, null);
            return res;
        }
        return 0;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        int op=matcher.match(uri);
        if (op == 0) {
            int res = mSqLiteDatabase.update("frequency",values,selection,selectionArgs);
            contentProvider.notifyChange(uri, null);
            return res;
        }
        return -1;
    }
}